<template>
  <view class="main">
    <u-navbar
      :title="params.functionName"
      back-icon-color="#fff"
      title-color="#fff"
      :background="{ backgroundColor: 'rgb(61, 95, 255)' }"
    >
    </u-navbar>
    <view class="u-p-20">
      <!-- <view class="search flex u-m-b-20">
        <view class="mk">
          <u-input
            class="myinput"
            :border="true"
            v-model="searchData.customerName"
            type="select"
            :select-open="mineShow"
            @click="mineShow = true"
            placeholder="请选择煤矿"
          />
        </view>
      </view> -->
      <view class="top-header">
        <div class="time-body">
          <view class="flex date">
            <u-button
              v-for="(obj, i) in dateTypeList"
              :key="obj"
              :type="searchData.btType === i ? 'primary' : 'default'"
              class="bt"
              @click.native="monthDay(i)"
              >{{ obj }}</u-button
            >
          </view>
        </div>
        <div class="time-body u-flex">
          <uni-datetime-picker
            type="date"
            :border="false"
            placeholder="请选择开始日期"
            :end="end"
            class="u-m-l-30"
            :clear-icon="false"
            return-type="string"
            v-model="searchData.beginDate"
            @change="changeDate('0')"
          />
          <text class="u-m-l-10 u-m-r-10">至</text>
          <uni-datetime-picker
            type="date"
            :border="false"
            placeholder="请选择结束日期"
            :start="start"
            class="u-m-r-30"
            :clear-icon="false"
            return-type="string"
            v-model="searchData.endDate"
            @change="changeDate('1')"
          />
        </div>
      </view>
    </view>

    <scroll-view
      class="content"
      :scroll-y="true"
      refresher-enabled="true"
      :refresher-triggered="triggered"
      :refresher-threshold="50"
      @scrolltolower="onScrollToLower"
      refresher-background="#F5F5F5"
      @refresherrefresh="onRefresh"
    >
      <template v-for="obj in mylist">
        <view :key="obj.id" class="my-card u-m-b-20 u-p-10" @click="info(obj)">
          <view class="u-flex u-row-between u-p-10">
            <view class="u-flex">
              <view class="u-flex-col">
                <view class="font-w u-font-lg">{{ obj.customerNameQx || obj.customerName }}</view>
                <view class="text-omit">{{ obj.installPlace }}</view>
              </view>
              <u-button
                v-if="obj.nowStatus && obj.nowStatus != '0'"
                size="mini"
                plain
                class="u-m-l-10"
                @click="goDetailBtn(obj)"
                >处置</u-button
              >
            </view>
            <view>
              <u-tag text="否" type="warning" v-if="obj.isComplete == '0' || !obj.isComplete" />
              <u-tag text="是" type="success" v-else />
            </view>
          </view>
          <u-line />

          <view class="u-p-10">
            <view><text class="font-w">异常波动持续时长（分钟）：</text>{{ obj.waveDuration }}</view>
            <view><text class="font-w">绝对瓦斯涌出量：</text>{{ obj.emiValue }}</view>
            <view><text class="font-w">风险指数：</text>{{ obj.areaPoint }}</view>
            <view><text class="font-w">高风险天数：</text>{{ obj.areaPointDays }}</view>
          </view>
        </view>
      </template>
      <template v-if="showEmpty">
        <view class="c-empty p-absolute-center">
          <u-empty text="抱歉，暂无相关数据~" :src="require('@/static/image/empty.png')"></u-empty>
        </view>
      </template>
      <view class="p-t-10 p-b-10" v-else>
        <u-loadmore :status="status" />
      </view>
    </scroll-view>

    <u-picker mode="selector" v-model="countyShow" :range="countyList" @confirm="confirm" range-key="label"></u-picker>
    <!-- <u-picker mode="selector" v-model="mineShow" :range="mineList" @confirm="mineConfirm" range-key="label"></u-picker> -->

    <!-- 煤矿企业 -->
    <u-popup mode="bottom" v-model="mineShow">
      <view class="popup-content">
        <view class="u-flex u-row-between u-p-b-30">
          <u-button :hair-line="false" :custom-style="customStyle" throttle-time="500" @click="cancelCustomer()"
            >取消</u-button
          >
          <u-button :hair-line="false" :custom-style="submitStyle" throttle-time="500" @click="clickCustomer()"
            >确定</u-button
          >
        </view>
        <view class="u-p-b-20">
          <u-search
            placeholder="请选择企业名称"
            v-model="filterCustomerVal"
            shape="square"
            bg-color="#E5EAE8"
            height="80"
            :show-action="true"
            :animation="true"
            :input-style="{ marginLeft: '20rpx' }"
            :search-icon="searchSrc"
            placeholder-color="#999999"
            :action-style="{
              color: '#288CFE',
              fontSize: '14px',
              fontWeight: '400',
            }"
          ></u-search>
        </view>
        <scroll-view scroll-y="true" style="height: 600rpx">
          <view class="w-100p checkbox">
            <u-radio-group active-color="#288CFE" width="100%" v-model="radioValue">
              <u-radio
                @change="checkboxCustomerChange"
                v-for="(item, index) in filterCustomerList"
                :key="index"
                :name="item.label"
              >
                {{ item.label }}
              </u-radio>
            </u-radio-group>
            <template v-if="filterCustomerList.length === 0">
              <view class="c-empty p-absolute-center">
                <u-empty text="抱歉，暂无相关数据~" :src="require('@/static/image/empty.png')"></u-empty>
              </view>
            </template>
          </view>
        </scroll-view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      dateTypeList: ["前一天", "后一天", "当日"],
      status: "loading",
      triggered: false, // 下拉刷新
      showEmpty: false,
      searchData: {
        btType: 0,
        countyNo: "",
        countyStr: "",
        // customerStr: '所有煤矿',
        customerCode: "", //企业编码
        customerName: "", //企业名称
        customerNo: "", // //企业编码
        beginDate: "",
        endDate: "",
        pageSize: 20,
        pageNumber: 1,
      },
      countyShow: false,
      mineShow: false,
      countyList: [],
      mineList: [],
      params: {},
      mylist: [],

      // 按钮样式
      searchSrc: require("@/static/image/search.png"),
      customStyle: {
        // 注意驼峰命名，并且值必须用引号包括，因为这是对象
        color: "#333333",
        background: "#F1F5F3",
        borderRadius: "20rpx",
        width: "40%",
        border: "none",
      },
      submitStyle: {
        color: "#fff",
        background: "#288CFE",
        borderRadius: "20rpx",
        width: "40%",
        border: "none",
      },
      radioValue: "",
      filterCustomerVal: "", //企业名称搜索数据
      arr: [],
      arrTwo: [],
      start: "",
      end: "",
    };
  },
  onLoad(obj) {
    this.params = JSON.parse(obj.item);
    this.init();
    this.initTime();
    this.searchData = { ...this.searchData, ...this.params };
    //console.log(this.params, this.searchData)
    //
    this.getCustomers();
  },
  onReady() {
    //
    this.getData();
  },
  computed: {
    filterCustomerList() {
      return this.mineList.filter((item) => {
        return this.filterCustomerVal
          ? item.label?.indexOf(this.filterCustomerVal) >= 0 ||
              item.pinyinCode?.indexOf(this.filterCustomerVal.toUpperCase()) >= 0
          : true;
      });
    },
  },
  methods: {
    /**
     * 初始化
     */
    init() {
      this.searchData.pageNumber = 1;
      this.status = "loading";
      this.showEmpty = false;
    },
    /**
     * 初始时间范围
     */
    initTime() {
      const { beginDate, endDate } = this.searchData;
      if (beginDate && endDate) {
        this.$nextTick(() => {
          this.start = this.$date(this.searchData.beginDate).substring(0, 10);
          this.end = this.$date(this.searchData.endDate).substring(0, 10);
        });
      } else {
        this.$set(this.searchData, "btType", 2);
        const date = this.$u.date();
        this.start = date.substring(0, 10);
        this.end = date.substring(0, 10);
        this.searchData.beginDate = this.start;
        this.searchData.endDate = this.end;
      }
    },
    changeDate() {
      this.$set(this.searchData, "btType", "");
      this.$nextTick(() => {
        this.start = this.$date(this.searchData.beginDate).substring(0, 10);
        this.end = this.$date(this.searchData.endDate).substring(0, 10);
        this.getData();
      });
    },
    monthDay(val) {
      const date = this.$u.date();
      this.searchData.btType = val;
      if (val === 0) {
        let timestamp =
          this.searchData.beginDate &&
          this.searchData.endDate &&
          new Date(this.$date(this.searchData.endDate).substr(0, 10) + " 00:00:00").getTime() -
            new Date(this.$date(this.searchData.beginDate).substr(0, 10) + " 00:00:00").getTime() <
            24 * 60 * 60000
            ? new Date(this.$date(this.searchData.beginDate).substr(0, 10) + " 00:00:00").getTime()
            : new Date(date.substr(0, 10) + " 00:00:00").getTime();
        // 前一天
        let prevTime = this.$date(timestamp - 24 * 60 * 60000);
        // 后一天
        let nextTime = this.$date(timestamp - 60000);

        this.searchData.beginDate = prevTime.substring(0, 10);
        this.searchData.endDate = nextTime.substring(0, 10);
      } else if (val === 1) {
        let timestamp =
          this.searchData.beginDate &&
          this.searchData.endDate &&
          new Date(this.$date(this.searchData.endDate).substr(0, 10) + " 00:00:00").getTime() -
            new Date(this.$date(this.searchData.beginDate).substr(0, 10) + " 00:00:00").getTime() <
            24 * 60 * 60000
            ? new Date(this.$date(this.searchData.beginDate).substr(0, 10) + " 23:59:59").getTime()
            : new Date(date.substr(0, 10) + " 23:59:59").getTime();
        // 前一天
        let prevTime = this.$date(timestamp + 60000);
        // 后一天
        let nextTime = this.$date(timestamp + 24 * 60 * 60000);

        this.searchData.beginDate = prevTime.substring(0, 10);
        this.searchData.endDate = nextTime.substring(0, 10);
      } else if (val === 2) {
        this.searchData.beginDate = date.substring(0, 10);
        this.searchData.endDate = date.substring(0, 10);
      } else if (val === 3) {
        this.searchData.beginDate = this.$timeScopeThisMonth()[0].substring(0, 10);
        this.searchData.endDate = date.substring(0, 10);
      }
      this.init();
      this.initTime();
      this.getData();
    },
    info(obj) {
      const { beginDate, endDate, customerNo } = this.searchData;
      const params = {
        beginDate: beginDate,
        endDate: endDate,
        customerNo: obj.customerNo || customerNo,
        customerNameQx: obj.customerNameQx || obj.customerName,
      };
      uni.navigateTo({
        url: `../gasInfo?item=${JSON.stringify(params)}`,
      });
    },
    goDetailBtn(obj) {
      const code = this.params.functionCode;
      //
      let params = {
        id: obj.id,
        customerName: obj.customerNameQx || obj.customerName,
        functionCode: code,
        detailType: obj?.detailType,
        functionTableName: obj.functionTableName,
        pageNumber: 1,
        pageSize: 20,
        sensorType: "",
        type: obj.type,
        isJtMine: true,
      };
      uni.navigateTo({
        url: `../chartInfo?item=${JSON.stringify(params)}`,
      });
    },
    handleSearch() {
      this.mylist = [];
      this.searchData.pageNumber = 1;
      this.status = "loading";
      this.showEmpty = false;
      this.getData();
    },
    onRefresh() {
      if (this.Isfreshing) return;
      this.Isfreshing = true;
      if (!this.triggered) {
        // 保证刷新状态下，triggered为true
        this.triggered = true;
        this.getData();
        setTimeout(() => {
          this.triggered = false; // 触发onRestore，关闭刷新图标
          this.Isfreshing = false;
        }, 1200);
      }
    },
    onScrollToLower() {
      if (this.status == "loading") {
        this.searchData.pageNumber++;
        this.getData();
      }
    },
    getCustomers() {
      this.$get("/guard/common/getCustomers?countyNo=" + this.params.countyNo).then((res) => {
        const { body } = res;
        if (Array.isArray(body)) {
          body.unshift({
            id: "",
            label: "所有煤矿",
          });
          this.mineList = body;
        }
      });
    },
    submitDate(obj) {
      console.log(obj);
      this.searchData.beginDate = obj.beginDate;
      this.searchData.endDate = obj.endDate;
      this.handleSearch();
    },
    async getData() {
      const {
        pageSize,
        pageNumber,
        beginDate,
        endDate,
        customerNo,
        countyNo,
        functionCode,
        functionTableName,
        typeCode,
        sensorType,
        functionName,
        isQueryType,
      } = this.searchData;
      const query = {
        beginDate,
        customerNo,
        endDate,
        functionCode,
        functionTableName,
        type: functionName,
        countyNo: countyNo,
        typeCode,
        sensorType,
        pageSize,
        pageNumber,
        isQueryType,
      };
      const { body } = await this.$post("/guard/anomalous/detail/dataList", query);
      if (Array.isArray(body.content)) {
        const myarr = body.content;
        this.mylist = this.searchData.pageNumber === 1 ? myarr : this.mylist.concat(myarr);
        // 到底了
        if (myarr.length < this.searchData.pageSize) {
          this.status = "nomore";
        }
        // 数据空
        if (this.searchData.pageNumber === 1 && this.mylist && this.mylist.length === 0) {
          this.showEmpty = true;
        } else {
          this.showEmpty = false;
        }
      } else {
        this.showEmpty = true;
      }
    },
    confirm(index) {},

    // 选中某个煤矿时，由radio触发
    checkboxCustomerChange(e) {
      if (e) {
        this.radioValue = e;
        this.arr = [e];
        for (let i = 0; i < this.mineList.length; i++) {
          if (this.mineList[i].label === e) {
            this.arrTwo = [this.mineList[i].id];
          }
        }
      }
      this.customerCode = this.arrTwo.toString();
      this.customerName = this.arr.toString();
      if (this.arr.toString() === "所有煤矿") this.customerName = "";
    },
    deleteOne(str, arr) {
      let index = arr.indexOf(str);
      arr.splice(index, 1);
      return arr;
    },
    // 煤矿企业数据初始化
    initCustomer() {
      if (this.searchData.customerName !== "") {
        this.arr = [];
        this.arrTwo = [];
        for (let i = 0; i < this.mineList.length; i++) {
          if (this.searchData.customerName?.indexOf(this.mineList[i].label) !== -1) {
            this.arr.push(this.mineList[i].label);
            this.arrTwo.push(this.mineList[i].id);
            this.$set(this.mineList[i], "checked", true);
          } else {
            this.$set(this.mineList[i], "checked", false);
          }
        }
        this.$set(this, "customerCode", this.arrTwo.toString());
        this.$set(this, "customerName", this.arr.toString());
        this.radioValue = this.searchData.customerName;
      } else {
        this.arr = [];
        this.arrTwo = [];
        for (let i = 0; i < this.mineList.length; i++) {
          this.$set(this.mineList[i], "disabled", false);
          this.$set(this.mineList[i], "checked", false);
        }
        this.$set(this, "customerCode", "");
        this.$set(this, "customerName", "");
        this.radioValue = "";
      }
    },
    // 煤矿企业数据取消
    cancelCustomer() {
      this.initCustomer();
      this.mineShow = false;
      this.filterCustomerVal = "";
    },
    // 煤矿企业数据确定
    clickCustomer(index) {
      this.$set(this.searchData, "customerNo", this.customerCode);
      this.$set(this.searchData, "customerCode", this.customerCode);
      this.$set(this.searchData, "customerName", this.customerName);
      this.filterCustomerVal = "";
      this.mineShow = false;
      this.handleSearch();
    },

    // mineConfirm(index) {
    //   this.searchData.customerStr = this.mineList[index].label
    //   if (this.mineList[index].label == '所有煤矿') {
    //     this.searchData.customerName = ''
    //   } else {
    //     this.searchData.customerName = this.searchData.customerStr
    //   }
    //   this.searchData.customerNo = this.mineList[index].id
    //   this.handleSearch()
    // },
  },
};
</script>
<style lang="scss" scoped>
// 背景
.main {
  background: #f7f7fa;
}
.my-card {
  border-radius: 6px !important;
  background: white;
}
.top-header {
  background: #fff;
  padding-top: 10px;
  padding-bottom: 10px;
  .date {
    margin: 10px 10px;
    /deep/ .u-btn--primary {
      color: #3d5fff;
      border-radius: 4px;
      border: 1px solid rgb(61, 95, 255);
      background: rgba(61, 95, 255, 0.1);
    }
    /deep/ .u-btn--default {
      color: #595959;
      border-radius: 4px;
      border: none;
      background: rgba(153, 153, 153, 0.1);
    }
    /deep/.u-hairline-border {
      &:after {
        border: none;
      }
    }
    /deep/ .u-size-primary {
      height: 30px;
      line-height: 30px;
    }
    /deep/ .u-size-default {
      height: 30px;
      line-height: 30px;
    }
    .bt {
      border-radius: 4px;
      flex: 1;
      margin: 0 5px;
      &:after {
        border-radius: 4px;
      }
    }
  }
}

.time-body {
  position: relative;
  width: 100%;
  /deep/.uni-date-x {
    background: rgba(153, 153, 153, 0.1) !important;
    color: #999999 !important;
    border-radius: 4px !important;
  }
}
.search {
  .xq {
    width: 8em;
  }

  .mk {
    flex: 1;
    margin-left: 1em;

    .u-input--border {
      border-radius: 22.5px;
    }
  }
}

.font-w {
  font-weight: bold;
}

.content {
  flex: 1;
  overflow: hidden;
  padding: 0 20rpx 20rpx 20rpx;
  box-sizing: border-box;
  background: inherit;
}

.my-title {
  text-decoration: underline;
  color: #409eff;
}

.myinput {
  background: white;
  border-color: white !important;
}
.popup-content {
  // 弹出层样式
  padding: 24rpx;
  text-align: center;
  .checkbox {
    &-item {
      height: 100rpx;
    }
    /deep/.u-checkbox-group {
      display: inline;
      .u-checkbox {
        border-bottom: 1px solid #dddddd;
        justify-content: space-between;
        flex-flow: row-reverse;
        .u-checkbox__icon-wrap {
          background: rgba(1, 72, 51, 0.2);
          border: none;
        }
      }
    }
    /deep/.u-radio-group {
      display: inline;
      .u-radio {
        border-bottom: 1px solid #dddddd;
        justify-content: space-between;
        flex-flow: row-reverse;
        height: 90rpx;
        .u-radio__icon-wrap {
          background: rgba(1, 72, 51, 0.2);
          border: none;
        }
      }
    }
  }
}
.text-omit {
  width: 400rpx;
  white-space: nowrap; /* 确保文本在一行内显示 */
  overflow: hidden; /* 超出容器部分隐藏 */
  text-overflow: ellipsis;
}
</style>
